package x.ovo.wechat.bot.common.http.request;

import lombok.Data;
import x.ovo.wechat.bot.common.util.WechatUtil;
import x.ovo.wechat.bot.common.exception.LoginException;

import java.io.Serializable;
import java.util.regex.Matcher;

/**
 * 基本请求参数 登陆后的所有接口都需要携带该类
 *
 * @author ovo on 2024/04/19.
 * @since 1.0.0
 */
@Data
public class BaseRequest implements Serializable {

    private String Skey;
    private String Sid;
    private String Uin;
    private String DeviceID;

    private transient String dataTicket;
    private transient String passTicket;
    private transient String authTicket;

    /**
     * 从xml解析baseRequest
     * <p>{@code
     * <error>
     * <ret>0</ret>
     * <message></message>
     * <skey>@crypt_jkde99da_b4xxxxxxxxxxxxxxx76d9yualp</skey>
     * <wxsid>8rwxxxxxxxxxHq2P</wxsid>
     * <wxuin>26xxx7</wxuin>
     * <pass_ticket>AFsdZ7eHxxxxxxxxxxxxxxxxfr1vjHPn=</pass_ticket>
     * <isgrayscale>1</isgrayscale>
     * </error>
     * }</p>
     *
     * @param xmlString XML 字符串
     * @return {@link BaseRequest}
     */
    public static BaseRequest from(String xmlString) {
        BaseRequest request = new BaseRequest();
        Matcher matcher = WechatUtil.matcher("<ret>(\\d+)</ret>", xmlString);
        if (matcher.find()) {
            if (!"0".equals(matcher.group(1))) {
                throw new LoginException("登录失败" + WechatUtil.match("<message>(\\s+)</message>", xmlString));
            }
        }
        request.setSkey(WechatUtil.match("<skey>(\\S+)</skey>", xmlString));
        request.setSid(WechatUtil.match("<wxsid>(\\S+)</wxsid>", xmlString));
        request.setUin(WechatUtil.match("<wxuin>(\\d+)</wxuin>", xmlString));
        request.setPassTicket(WechatUtil.match("<pass_ticket>(\\S+)</pass_ticket>", xmlString));
        request.setDeviceID(WechatUtil.generateDeviceId());
        return request;
    }

}
